function createNode(w, addBtns, id) {
  if (!id) id = `${generateGuid()}`;
  let uk_speech = w["uk-speech"];
  let us_speech = w["us-speech"];
  if (uk_speech && uk_speech.length > 10) {
    uk_speech = uk_speech
      .replaceAll("\\", "")
      .replaceAll("\\", "")
      .replaceAll('"', "");
  } else uk_speech = false;
  if (us_speech && us_speech.length > 10) {
    us_speech = us_speech
      .replaceAll("\\", "")
      .replaceAll("\\", "")
      .replaceAll('"', "");
  } else us_speech = false;
  let content = "";
  if (!addBtns) {
    content = `
    <div class='w1'>
      <div class='word'>${w.word}</div>
      <div>
        <div class='pronounce'>
        发音:${w.pronounce == null ? "-" : w.pronounce}
        <button class="audio-btn" onclick="playAudio('${uk_speech}')">英</button>
        <button class="audio-btn" onclick="playAudio('${us_speech}')">美</button>
        </div>
    
        <div class='trans'>
        ${w.trans}</div>
      </div>
      
    <div class='w2' id='${id}'>
      <div class='ielst' 
        style="background-color:${w.ielst === "YES" ? "#ff6666" : "#aaaaaa"}">
        IELST:${w.ielst == null ? "-" : w.ielst}</div>
    
        <div class='ok' isok='${w.ok}'
        onclick="setOK('${id}','${w.word}','${w.ok}')"
        title="click me to mark this word OK"
        style="background-color:${w.ok == "OK" ? "#00ff00" : "#cccc00"}">
        ${w.ok != "OK" ? "不认识" : "认识"}</div>
    </div>
    </div>
    `;
  } else {
    content = `
      <div class='w' id='${id}'>
      <div class='word'>${w.word}</div>
  
      <div class='pronounce'>
      发音:${w.pronounce == null ? "-" : w.pronounce}
      <button class="audio-btn" onclick="playAudio('${uk_speech}')">英</button>
      <button class="audio-btn" onclick="playAudio('${us_speech}')">美</button>
      </div>
  
      <div class='trans'>
      ${w.trans}</div>
  
      <div class='ielst' 
      style="background-color:${w.ielst === "YES" ? "#ff6666" : "#aaaaaa"}">
      IELST:${w.ielst == null ? "-" : w.ielst}</div>
  
      <div class='ok' isok='${w.ok}'
      onclick="setOK('${id}','${w.word}','${w.ok}')"
      title="click me to mark this word OK"
      style="background-color:${w.ok == "OK" ? "#00ff00" : "#aaaa00"}">
      ${w.ok != "OK" ? "不认识" : "认识"}</div>
      `;
    content += `
              <div class='btn similary' onclick="getAll('${id}','${w.word}')">查我</div>
          `;
  }
  content += `</div>`;

  return content;
}
function playAudio(audioUrl) {
  if (!audioUrl || audioUrl === "#") {
    // alert("暂无发音资源");
    return;
  }

  const audio = new Audio(audioUrl);
  audio.play().catch((e) => {
    console.error("音频播放失败:", e);
    // alert("无法播放音频，请检查网络连接或文件路径");
  });
}
/**
 * 添加主单词
 * @param {object} w
 */
function setRoot(w) {
  $(".directResult").html(createNode(w));
}

/**
 * 新增节点
 * @param {string} pid
 * @param {object} w
 */
function addNode(pid, w) {
  const id = `${generateGuid()}`;
  $(`#${pid}`).append(createNode(w, true, id));
}
/**
 * 创建节点
 * @param {string} pID
 * @param {Array} words
 */
function createNodes(pID, words) {
  for (let i = 0; i < words.length; i++) {
    if (pID === "directResult") {
      setRoot(words[i]);
      continue;
    }
    addNode(pID, words[i]);
  }
}
/**
 * 标记是否认识
 * @param {string} id
 * @param {object} w
 * @param {string} ok
 */
function setOK(id, w, ok) {
  const theCallback = function () {
    if ("OK" === $(`#${id} .ok`).attr("isok")) {
      $(`#${id} .ok`).css({ "background-color": "#cccc00" });
      $(`#${id} .ok`).html("不认识");
      $(`#${id} .ok`).attr("isok", "NO");
    } else {
      $(`#${id} .ok`).css({ "background-color": "#00ff00" });
      $(`#${id} .ok`).html("认识");
      $(`#${id} .ok`).attr("isok", "OK");
    }
  };
  $.get(`setOK?str=${w}`, theCallback, "json");
}
/**
 * Ajax 查询
 * @param {string} url
 * @param {Function} cb
 */
function get(url, cb) {
  const theCallback = function (data) {
    cb(data.info);
  };
  $.get(url, theCallback, "json");
}
/**
 * 查词
 * @param {string} id
 * @param {object} w
 * @returns void
 */
function getAll(id, w) {
  if (id) {
    $(".input").val(w);
  }
  const theW = getInputVal();
  if (!theW || theW === "") {
    return;
  }
  getEqual();
  getSimilary();
  getInclude();
  getPrefix();
  getSuffix();
}

function getSimilary() {
  create("getByKeyStrSimilary", "similary");
}
function getInclude() {
  create("getByKeyStrInclude", "include");
}
function getPrefix() {
  create("getByKeyStrPrefix", "prefix");
}
function getSuffix() {
  create("getByKeyStrSuffix", "suffix");
}
/**
 * 获取单词
 */
function getEqual() {
  let w = getInputVal();
  $(".directResult").html(`正在查询的单词:${w}`);
  let parendid = "directResult";
  get(`/getByKeyStrEqual?str=${w}`, (data) => {
    createNodes(parendid, data);
  });
}
/**
 * 构建查询
 * @param {string} url
 * @param {*} pid
 */
function create(url, pid) {
  $(`#${pid}`).html("");
  let w = getInputVal();
  let onlyIELST = $("input[name=ielst]").prop("checked");
  let onlyOK = $("input[name=ok]").prop("checked");

  get(`${url}?str=${w}&onlyIELST=${onlyIELST}&onlyOK=${onlyOK}`, (data) => {
    createNodes(`${pid}`, data);
  });
}
function createInclude(parendid) {
  createNodes(parendid, words);
}
function createPrefix(parendid) {
  createNodes(parendid, words);
}
function createSuffix(parendid) {
  createNodes(parendid, words);
}
function getInputVal() {
  return $(".input").val().trim().toLowerCase();
}

var timer = null;
function loaded() {
  $("input[type='checkbox']").on("change", function () {
    getAll();
  });
  $(".input").keydown(function (event) {
    if (event.keyCode == 13) {
      getAll();
    }
  });
  $(".input").on("input", function (e) {
    if (e.target.value) {
      document.title = `${e.target.value} - Eng`;
    } else {
      document.title = "Eng";
    }
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      getAll();
    }, 500);
  });
}
function generateGuid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return (
    s4() +
    s4() +
    "-" +
    s4() +
    "-" +
    s4() +
    "-" +
    s4() +
    "-" +
    s4() +
    s4() +
    s4()
  );
}
